今天承接昨天獲取網路流量的程式,將資料繪製成圖形.
一般的網管系統所提供多為簡單的線圖,我們自己撰寫的程式,
就可以有多種的組合方式,今天先介紹基本的圖形.
以下為程式:
#!/usr/bin/env python
# ---------------------------
# Python RRDTool
# Net Data
# Create Image from rrd file
# For IT Help
# ---------------------------
import rrdtool
import datetime
def net_graph(rrdfile, nettype, period):
timenow = datetime.datetime.now()
disptime = datetime.datetime.strftime(timenow, '%Y-%m-%d %H-%M-%S')
vlabel = '--vertical-label=Bytes / Sec'
title = 'eth0_%s_%s' % (nettype, period)
filename = title + '.png'
if period == 'yesterday':
start = 'end-1d'
end = '00:00'
if period == 'today':
start = '00:00'
end = '23:59'
if nettype == 'traffic_in':
showstr = 'In'
ds = 'net0_bytes_in'
data = 'rx'
kdata = 'krx'
color = '#1E90FFAA'
if nettype == 'traffic_out':
showstr = 'Out'
ds = 'net0_bytes_out'
data = 'tx'
kdata = 'ktx'
color = '#FF1493AA'
#
def_ds = 'DEF:%s=%s:%s:AVERAGE' % (data, rrdfile, ds)
cdef = 'CDEF:%s=%s,1024,/' % (kdata, data)
vdefavg = 'VDEF:avg=%s,AVERAGE' % data
graph_cmd = 'AREA:%s%s:%s' % (data, color, showstr)
avgrule = 'HRULE:avg#CBFF75:Average'
last_print = 'GPRINT:%s' % kdata
last_print = last_print + ':LAST:Current\\: %.2lfKBytes'
avg_print = 'GPRINT:%s' % kdata
avg_print = avg_print + ':AVERAGE:Average\\: %.2lfKBytes'
min_print = 'GPRINT:%s' % kdata
min_print = min_print + ':MIN:Min\\: %.2lfKBytes'
max_print = 'GPRINT:%s' % kdata
max_print = max_print + ':MAX:Max\\: %.2lfKBytes\\n'
# -------------------
rrdtool.graph(
filename,
'--start', start,
'--end', end,
'--title', title,
'-a', 'PNG',
'-W', 'Hitomitanaka for ITHelp',
'--slope-mode',
vlabel,
'--rigid',
'--width', '500',
'--height', '150',
'--x-grid', 'HOUR:1:HOUR:2:HOUR:2:0:%H',
'--alt-y-grid',
'--color', 'BACK#000000',
'--color', 'CANVAS#000000',
'--color', 'FONT#FFF978',
'--font=LEGEND:7',
'--font', 'TITLE:8:',
'--font', 'UNIT:7:',
'--font', 'WATERMARK:9',
# ---------------------------------
def_ds,
cdef,
vdefavg,
graph_cmd,
last_print,
avg_print,
min_print,
max_print,
avgrule,
'COMMENT:Update Time %s' % disptime
)
#
def draw_net(period):
net_graph('net.rrd', 'traffic_in', period)
net_graph('net.rrd', 'traffic_out', period)
if __name__ == '__main__':
draw_net('today')
draw_net('yesterday')
昨天的in
昨天的out
今天的in
今天的out
圖形上另有繪製一條水平線,為流量平均值.以方便了解平均流量.